package com.neusoft.neu24.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.neusoft.neu24.Result.CommonResult;
import com.neusoft.neu24.Result.ResultCode;
import com.neusoft.neu24.constants.RedisConstants;
import com.neusoft.neu24.dto.GridDTO;
import com.neusoft.neu24.dto.GridorDTO;
import com.neusoft.neu24.entity.Grid;
import com.neusoft.neu24.entity.Gridor;
import com.neusoft.neu24.mapper.GridMapper;
import com.neusoft.neu24.service.IGridService;
import com.neusoft.neu24.utils.fillGrid;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.neusoft.neu24.constants.RedisConstants.*;

@Service
public class GridServiceImpl implements IGridService {

    @Resource
    private GridMapper gridMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public List<Grid> listAll() {
        List<Grid> grids = gridMapper.listAll();
        return fillGrid.list2Tree(grids).getChildren();
    }

    @Override
    public CommonResult<List<GridDTO>> listAll2DTO() {
        String pcr = stringRedisTemplate.opsForValue().get(CACHE+"pcr");
        if (pcr != null) {
            try {
                return CommonResult.success(new ObjectMapper().readValue(pcr, new TypeReference<List<GridDTO>>() {}));
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        List<Grid> grids = gridMapper.listAll();
        List<Grid> children = fillGrid.list2Tree(grids).getChildren();

        List<GridDTO> dtos = BeanUtil.copyToList(children, GridDTO.class);

        try {
            stringRedisTemplate.opsForValue().set(CACHE+"pcr", new ObjectMapper().writeValueAsString(dtos));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return CommonResult.success(dtos);
    }

    @Override
    public CommonResult<List<String>> getPCRByIds(List<Integer> ids) {
        return CommonResult.success(gridMapper.getPCRByIds(ids));
    }

    @Override
    public CommonResult<List<Gridor>> getGridorsByGid(Integer gid) {
        List<Gridor> gridors = gridMapper.getGridorsByGid(gid);
        if(gridors.isEmpty()) return CommonResult.failed(ResultCode.DATA_ERROR);
        return CommonResult.success(gridors);
    }

    @Override
    public List<Grid> fillContent() {
        List<Grid> grids = gridMapper.listAll();
        List<Grid> children = fillGrid.list2Tree(grids).getChildren();
        List<Grid> contents = fillGrid.fillContent(children);
        gridMapper.deleteByIds(contents);
        gridMapper.insert(contents);
        return contents;
    }

    @Override
    public CommonResult<List<Integer>> getPids(Integer id) {
        String pids = (String) stringRedisTemplate.opsForHash().get("nep_grid_pids", id.toString());
        if (pids!=null && !pids.isEmpty()) {
            List<Integer> list = JSONObject.parseObject(pids, List.class);
            if (list != null && !list.isEmpty()) return CommonResult.success(list);
        }

        List<Integer> ids = gridMapper.getIdsById(id);
        if(ids.isEmpty() || ids == null) return CommonResult.failed(ResultCode.DATA_ERROR);
        return CommonResult.success(ids);
    }

    //通过省市区 末级id 轮询
    public List<Integer> getPidsBySelect(Integer id){
        List<Integer> ids = new ArrayList<>();
        List<Grid> gridList = new ArrayList<>();

        Grid grid = gridMapper.getPid(id);
        for(int j = id ;grid != null && grid.getLevel() > 1&&grid.getPid()!=1; j = grid.getPid(),grid = gridMapper.getPid(j)) {
            gridList.add(grid);
        }

        for (int i = gridList.size() - 1; i >= 0; i--) {
            ids.add(gridList.get(i).getPid());
        }
        ids.add(id);
        return ids;
    }


    @Override
    public CommonResult<List<Grid>> fillGridRelation() {
        System.out.println(stringRedisTemplate.opsForHash().size(CACHE+"grid:pids"));
        if (stringRedisTemplate.opsForHash().size(CACHE+"grid:pids") > 0) {
            return CommonResult.success(null);
        }

        List<Grid> grids = gridMapper.listAll();
        List<Grid> children = fillGrid.list2Tree(grids).getChildren();
        List<Grid> contents = fillGrid.fillGridRelation(children);
        if (gridMapper.getSize() > 0)
        gridMapper.deleteAll();

        HashMap<String, String> map = new HashMap<>();
        for (Grid g : contents) {
            List<Integer> pidsBySelect = getPidsBySelect(g.getId());
            map.put(g.getId().toString(), JSONObject.toJSONString(pidsBySelect));

            gridMapper.insertRelations(pidsBySelect,g.getId());
        }

        stringRedisTemplate.opsForHash().putAll(CACHE+"grid:pids",map);
        return CommonResult.success(contents);
    }

    @Override
    public CommonResult<Grid> getGrid(Integer id) {
        return CommonResult.success(gridMapper.getGrid(id));
    }

    @Override
    public CommonResult<List<GridorDTO>> getGridors(Integer id) {
        List<Integer> ids = gridMapper.getGridorIds(id);
        if (ids.isEmpty()) return CommonResult.failed(ResultCode.DATA_ERROR);
        List<GridorDTO> gridors = gridMapper.getGridorsByIds(ids);
        if (gridors.isEmpty()) return CommonResult.failed(ResultCode.DATA_ERROR);
        return CommonResult.success(gridors);
    }



}
